import time
import random  # 添加 random 模块

from loguru import logger
from playwright.sync_api import sync_playwright
import bit_api
from EmailManager import get_signup_link
from cf import bypass
from generate_full_name_tool import generate_sign_in_data
from smsactivate.api import SMSActivateAPI
class EmailSender:
    def __init__(self):
        self.browser = None
        self.context = None
        self.page = None

        self.tokens = None
        self.sensitive_id = None

    def intercept_setup_response(self, response):

        if 'https://auth0.openai.com/oauth/token' in response.url:
            if response.status == 200:
                content_json = response.json()
                logger.debug(f'获取Platform-Token成功 {content_json}')
                self.tokens = content_json
        if 'api.openai.com/dashboard/onboarding/login' in response.url:
            if response.status == 200:
                content_json = response.json()
                if content_json:  # 确保 content_json 不是 None
                    if 'user' in content_json and content_json['user'] is not None:
                        if 'session' in content_json['user']:
                            sensitive_id = content_json["user"]["session"]["sensitive_id"]
                            logger.debug(f'获取sensitive_id成功 {sensitive_id}')
                            self.sensitive_id = sensitive_id
                else:
                    logger.debug(f"字段 'content_json' 不存在于中")

    def check_url(self, url):
        self.page.goto(url)
        self.page.wait_for_load_state('load')
        time.sleep(5)
        bypass(self.page)

    def send_email(self):
        # "puubfsyostkj@hotmail.com----ISNXvxta139"
        username = "ikytrsesdsdfs23esda@autogpt-zh.com"
        email_pwd = "SOSodgdsf12vz096"
        password, full_name, bir = generate_sign_in_data()

        with sync_playwright() as p:
            signup_url = "https://platform.openai.com/signup/"
            broid = 'dc131fc488da4a3ab73da080b9f282d3'
            res = bit_api.openBrowser(broid)
            bit_api.updateBrowser(broid)
            if res['success']:
                ws = res['data']['ws']
            self.browser = p.chromium.connect_over_cdp(endpoint_url=ws)
            self.context = self.browser.new_context()

            self.page = self.context.new_page()
            self.check_url(signup_url)
            self.page.on("response", self.intercept_setup_response)
            self.page.get_by_label("Email address").click()
            self.page.get_by_label("Email address").fill(username)
            self.page.get_by_role("button", name="Continue", exact=True).click()
            self.page.get_by_label("Password").click()
            self.page.get_by_label("Password").fill(password)

            self.page.get_by_role("button", name="Continue").click()
            # self.page.wait_for_load_state('load')
            # link_url = fetch_email_from_openai("vileanna8959@hotmail.com", "SgR7l6uTa")

            error_message_element = self.page.query_selector('.ulp-input-error-message')
            if error_message_element:
                error_message_text = error_message_element.inner_text()
                if "The user already exists" in error_message_text:

                    print("已经注册")
                    return None
                else:
                    print("已经注册--其他")
                    return None

            prompt_alert_element = self.page.query_selector('#prompt-alert')
            if prompt_alert_element:
                prompt_alert_element_text = prompt_alert_element.inner_text()
                if "Too many signups from the same IP" in prompt_alert_element_text:
                    print("换IP")
                else:
                    print("换IP--其他")

            self.page.wait_for_selector('.onb-page.onb-verify-email')
            verify_email_element = self.page.query_selector('.onb-page.onb-verify-email')
            if verify_email_element:
                time.sleep(5)
                link_url = get_signup_link("vileanna8959@hotmail.com", "SgR7l6uTa", username)

            if not link_url:
                link_url = get_signup_link("vileanna8959@hotmail.com", "SgR7l6uTa", username)
                if not link_url:
                    return False
            logger.debug(f"link_url = {link_url}")
            self.check_url(link_url)
            self.page.wait_for_load_state('load')
            self.page.get_by_placeholder("Full name").click()
            self.page.get_by_placeholder("Full name").fill(full_name)

            input_element = self.page.query_selector('input[placeholder="Birthday"]')
            input_element.click()

            # 逐个输入日期信息
            for char in str(bir):
                input_element.press(char, delay=random.randint(2, 5))

            self.page.get_by_role("button", name="Agree").click()
            self.page.wait_for_load_state('load')
            time.sleep(5)
            self.page.goto("https://platform.openai.com/onboarding")

            while self.sensitive_id is None:
                time.sleep(5)

            self.context.close()
            self.browser.close()

if __name__ == '__main__':

    sender = EmailSender()
    sender.send_email()

    # fetch_email_from_openai("dshkjhafsafkj@hotmail.com","SgR7l6uTa")
    #

